﻿using System.Linq;

using ParamsDict = System.Collections.Generic.IDictionary<string, string>;

namespace QuickTuner.RadioProtocol.Modules
{
    public class StationsModule : ProtocolModuleBase
    {
        public override string Name { get { return "STATIONS"; } }

        public StationsModule() { }
        public StationsModule(IRadio target) : base(target) { }

        // methods ______________________________________________________________________

        protected override void OnInitActions()
        {
            RegisterAction("ADD", CanAdd, Add);
            RegisterAction("REMOVE", CanRemove, Remove);
        }

        public bool CanAdd(ParamsDict parameters)
        {
            var requiredKeys = new[] { "title", "station_url" };

            return requiredKeys.All(key =>
                parameters != null &&
                parameters.ContainsKey(key) &&
                !string.IsNullOrEmpty(parameters[key]));
        }

        public void Add(ParamsDict parameters)
        {
            var s = new Station {
                Title = parameters["title"],
                StationURL = parameters["station_url"]
            };

            Target.Stations.Add(s);
        }

        public bool CanRemove(ParamsDict parameters)
        {
            return Target.Stations.Any(s =>
                parameters != null &&
                s.Title == parameters["title"] &&
                s.StationURL == parameters["station_url"]);
        }

        public void Remove(ParamsDict parameters)
        {
            Target.Stations.RemoveAll(s =>
                s.Title == parameters["title"] &&
                s.StationURL == parameters["station_url"]);
        }
    }
}
